package com.hunan.api.catv.service.biz.tasks;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.TaskType;
import com.hunan.api.catv.entity.po.Tasks;
import com.hunan.api.catv.entity.vo.TasksVo;
import com.hunan.api.catv.mq.MqConstants;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.impl.tasks.TasksService;
import com.hunan.api.catv.utils.GsonUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class TasksBiz extends ResultService {

    @Autowired
    TasksService tasksService;

    @Autowired
    AmqpTemplate amqpTemplate;

    public ServiceResult submit(Integer type, String params) {
        Tasks tasks = new Tasks();
        tasks.setType(type);
        tasks.setDetail(params);
        tasks.setState(2);
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"));
        String name = TaskType.getResult(type) + currentTime + ".xls";
        tasks.setName(name);
        ServiceResult addResult = tasksService.add(tasks);
        if (addResult.getStatus()) {
            JsonObject msg = new JsonObject();
            msg.addProperty("type", type);
            msg.addProperty("params", params);
            msg.addProperty("taskId", tasks.getTaskId());
            msg.addProperty("name", name);
            amqpTemplate.convertAndSend(MqConstants.tasks_exchange, MqConstants.tasks_key, GsonUtils.toJson(msg));
            return buildOK(true, "创建导出任务成功");
        }
        return buildFail(false, "创建导出任务失败");
    }

    public PageInfo<TasksVo> page(Integer pageNum, Integer pageSize, Integer type) {
        PageHelper.startPage(pageNum, pageSize);
        Tasks tasks = new Tasks();
        tasks.setType(type);
        List<TasksVo> list = tasksService.list(tasks);
        return new PageInfo<TasksVo>(list);
    }

    public ServiceResult update(Tasks tasks) {
        return tasksService.update(tasks);
    }
}
